package com.videoaggre.zcl.parse.impl

import android.net.Uri
import androidx.core.text.isDigitsOnly
import com.alibaba.fastjson.JSON
import com.videoaggre.zcl.bean.*
import com.videoaggre.zcl.utils.Logger
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.util.*

object AgefansParse {
    @JvmField
    val HOME = "https://www.agefans.net"

    @JvmField
    val LAST_UPDATED = "$HOME/update"

    @JvmField
    val TODAY_RECOMMENDED = "$HOME/recommend"

    @JvmField
    val PLAYER = "$HOME/age/player/ckx1/?url"

    @JvmStatic
    fun createDetailLink(id: String) = "$HOME/detail/${id}"

    /*companion object {
        private const val HOME = "https://www.agefans.tv/"
        //https://www.agefans.tv/play/20190373?playid=2_1
    }*/
    @JvmStatic
    fun parseHome(html: String, successCallback: (AgefansHome) -> Unit) {
        val mAgefansHome = AgefansHome()
        mAgefansHome.lastUpdatedMoreLink = LAST_UPDATED
        mAgefansHome.todayRecommendedMoreLink = TODAY_RECOMMENDED
        val result = kotlin.runCatching {
            Jsoup.parse(html).run {
                select(".div_left .blockcontent").forEachIndexed { index, element ->
                    element.select(".anime_icon1").forEach {
                        when (index) {
                            0 -> if (mAgefansHome.todayRecommendeds.size < 9)
                                mAgefansHome.todayRecommendeds.add(it.toAgefansItem())
                            1 -> if (mAgefansHome.lastUpdateds.size < 9)
                                mAgefansHome.lastUpdateds.add(it.toAgefansItem())
                        }
                    }
                }
            }
            val newAnimeStart = "var new_anime_list ="
            val newAnimeEnd = "}];"
            val startIndex = html.indexOf(newAnimeStart)
            mAgefansHome.timeTables =
                arrayListOf<NewAnime>().also { it.addAll(JSON.parseArray(html.substring(startIndex + newAnimeStart.length, html.indexOf(newAnimeEnd, startIndex) + newAnimeEnd.length - 1), NewAnime::class.java) ?: arrayListOf()) }
        }.also { Logger.e(it.exceptionOrNull()) }
        successCallback.invoke(mAgefansHome)
    }

    @JvmStatic
    fun parseDetails(html: String, successCallback: (AgefansDetails) -> Unit) {
        val mAgefansDetails = AgefansDetails()
        val result = kotlin.runCatching {
            Jsoup.parse(html).run {
                mAgefansDetails.name = select(".detail_imform_name").text()
                mAgefansDetails.cover = "${
                    select(".poster").attr("src").let {
                        if (it.startsWith("https") || it.startsWith("http"))
                            it
                        else
                            "https:${it}"
                    }
                }"
                mAgefansDetails.intro = select(".detail_imform_desc_pre p").last().text()
                select(".detail_imform_kv").forEach { mAgefansDetails.tags.add(AgefansDetailsTag(it.select(".detail_imform_tag").text(), it.select(".detail_imform_value").text())) }
                select(".movurl").forEach {
                    val movurl = it.select("a")
                    if (movurl.size > 0) {
                        mAgefansDetails.series.add(mutableListOf<AgefansDetailsSerie>().apply { movurl.forEach { add(AgefansDetailsSerie(it.text(), HOME + it.attr("href"))) } })
                    }
                }
                select(".relates_series a").forEach {
                    mAgefansDetails.relatesSeries.add(AgefansItem(it.text(), HOME + it.attr("href")))
                }
                select("#recommend_block .anime_icon1").forEach { mAgefansDetails.recommends.add(it.toAgefansItem()) }
            }
        }
        successCallback.invoke(mAgefansDetails)
    }

    @JvmStatic
    fun parseSerie(html: String, successCallback: (palyerLink: String) -> Unit) {
        kotlin.runCatching {
            Jsoup.parse(html).run {
                val src = select("#age_playfram").attr("src")
                successCallback.invoke(src.let { if (!it.startsWith("http")) "${HOME}$it" else it })
            }
        }
        Logger.e(html)
    }

    @JvmStatic
    fun parseSerieLink(html: String, successCallback: (palyerLink: String) -> Unit) {
        kotlin.runCatching {
            Jsoup.parse(html).run {
                successCallback.invoke(select("video").last().attr("src"))
            }
        }
//        Logger.e(html)
    }

    @JvmStatic
    fun createSearchLink(query: String, page: Int) = "$HOME/search?query=${query}&page=${page}"

    @JvmField
    val getIndexArr = arrayOf(0, 3, 4, 5, 6)

    @JvmStatic
    fun parseSearch(html: String, successCallback: (page: AgefansPage<AgefansItem>) -> Unit) {
        kotlin.runCatching {
            val mAgefansPage = AgefansPage<AgefansItem>()
            val agefansItems = mutableListOf<AgefansItem>()
            Jsoup.parse(html).run {
                select(".blockcontent1 .cell").forEach {
                    val tags = mutableListOf<AgefansDetailsTag>()
                    it.select(".cell_imform_kv").forEachIndexed { index, element ->
                        if (index in getIndexArr) {
                            tags.add(AgefansDetailsTag(element.select(".cell_imform_tag").text(), element.select(".cell_imform_value").text()))
                        }
                    }
                    agefansItems.add(
                        AgefansItem(
                            it.select(".cell_imform_name").text(),
                            HOME + it.select("a").attr("href"),
                            "https:${it.select("img").let { it.attr("src").ifEmpty { it.attr("data-src") } }}",
                            it.select(".newname").text(),
                            tags
                        )
                    )
                }
                mAgefansPage.data = agefansItems
                handPage(this, mAgefansPage)
                successCallback.invoke(mAgefansPage)
            }
        }.also { Logger.e(it.exceptionOrNull()) }
    }

    @JvmStatic
    fun createUpdateLink(page: Int) = "$HOME/update?page=${page}"

    @JvmStatic
    fun parseLastUpdate(html: String, successCallback: (page: AgefansPage<AgefansItem>) -> Unit) {
        kotlin.runCatching {
            val mAgefansPage = AgefansPage<AgefansItem>()
            val agefansItems = mutableListOf<AgefansItem>()
            Jsoup.parse(html).run {
                select(".anime_icon2").forEach {
                    agefansItems.add(
                        AgefansItem(
                            it.select(".anime_icon2_name a").text(),
                            HOME + it.select(".anime_icon2_name a").attr("href"),
                            "https:${it.select(".anime_icon2_img").let { it.attr("src").ifEmpty { it.attr("data-src") } }}",
                            it.select(".anime_icon1_name1").text(),
                        )
                    )
                }
                mAgefansPage.data = agefansItems
                handPage(this, mAgefansPage)
                successCallback.invoke(mAgefansPage)
            }
        }.also { Logger.e(it.exceptionOrNull()) }
    }

    @JvmStatic
    fun createRecommendLink(page: Int) = "$HOME/recommend?page=${page}"

    @JvmStatic
    private fun handPage(element: Element, mAgefansPage: AgefansPage<*>) {
        mAgefansPage.totalCount = element.select("#result_count").first()?.text()?.let {
            var total = ""
            it.toCharArray().forEach {
                if (Character.isDigit(it)) {
                    total += it
                }
            }
            total.toInt()
        } ?: 0
        val href = element.select(".pbutton").last()?.attr("href")
        val uri = Uri.parse(HOME + (href ?: ""))
        var page = uri.getQueryParameter("page")
        if (page == null) {
            // 目录方式再次读取
            href?.run {
                agefansCatalogTypeValueOrder().forEach {
                    val indexText = it.alias.ifEmpty { it.typeName }
                    val index = indexOf(indexText)
                    if (-1 != index) {
                        val startIndex = index + indexText.length + 1
                        val catalogTotalPage = substring(startIndex, indexOf("-", startIndex))
                        if (catalogTotalPage.isDigitsOnly()) {
                            page = catalogTotalPage
                        }
                    }
                }
            }
            // 没找到要不是最后一页要不就一条记录没有
        }
        mAgefansPage.totalPage = page?.toInt() ?: 0
        mAgefansPage.currentPage = element.select(".pbutton_current").let {
            it.forEach { element ->
                if (element.text().isDigitsOnly())
                    return@let element.text().toInt()
            }
            1
        }
        mAgefansPage.totalPage = if (0 == mAgefansPage.totalPage) mAgefansPage.currentPage else mAgefansPage.totalPage
    }

    @JvmStatic
    fun createCatalogLink(catalogs: MutableMap<String, String>): String {
        var link = "$HOME/catalog/version-year-initial-type-resources-order-page-region-quarter-status"
        catalogs.entries.forEach {
            link = link.replace(it.key, it.value)
        }
        Logger.e("link==>$link")
        return link
    }

    private fun agefansCatalogTypeValueOrder() = mutableListOf<AgefansCatalogTypeValue>().apply {
        add(AgefansCatalogTypeValue("更新时间", "time", true))
        add(AgefansCatalogTypeValue("名称", "name"))
        add(AgefansCatalogTypeValue("点击量"))
    }

    fun agefansCatalogTypeValueYear() = mutableListOf<AgefansCatalogTypeValue>().apply {
        add(AgefansCatalogTypeValue("全部", "all", true))
        val year = Calendar.getInstance().get(Calendar.YEAR)
        for (i in 0 until (year - 2000)) {
            add(AgefansCatalogTypeValue("${year - i}"))
        }
        add(AgefansCatalogTypeValue("2000以前", "2000"))
    }

    fun catalogs(): MutableList<AgefansCatalogType> =
        mutableListOf<AgefansCatalogType>().apply {
            add(AgefansCatalogType("region", "地区", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                add(AgefansCatalogTypeValue("日本"))
                add(AgefansCatalogTypeValue("中国"))
                add(AgefansCatalogTypeValue("欧美"))
            }))
            add(AgefansCatalogType("version", "版本", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                add(AgefansCatalogTypeValue("TV"))
                add(AgefansCatalogTypeValue("剧场版"))
                add(AgefansCatalogTypeValue("OVA"))
            }))
            add(AgefansCatalogType("initial", "首字母", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                arrayOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z").forEach { add(AgefansCatalogTypeValue(it)) }
            }))
            add(AgefansCatalogType("year", "年份", agefansCatalogTypeValueYear()))
            add(AgefansCatalogType("quarter", "季度", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                add(AgefansCatalogTypeValue("1月", "1"))
                add(AgefansCatalogTypeValue("4月", "4"))
                add(AgefansCatalogTypeValue("7月", "7"))
                add(AgefansCatalogTypeValue("10月", "10"))
            }))
            add(AgefansCatalogType("status", "状态", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                add(AgefansCatalogTypeValue("连载"))
                add(AgefansCatalogTypeValue("完结"))
                add(AgefansCatalogTypeValue("未播放"))
            }))
            add(AgefansCatalogType("type", "类型", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                arrayOf(
                    "搞笑", "运动", "励志", "热血", "战斗", "竞技", "校园", "青春", "爱情", "冒险", "后宫", "百合", "治愈", "萝莉", "魔法",
                    "悬疑", "推理", "奇幻", "科幻", "游戏", "神魔", "恐怖", "血腥", "机战", "战争", "犯罪", "历史", "社会", "职场", "剧情",
                    "童年", "教育", "亲子", "真人", "歌舞", "肉番", "美少女", "轻小说", "吸血鬼", "乙女向", "泡面番", "欢乐向", "伪娘", "耽美"
                ).forEach { add(AgefansCatalogTypeValue(it)) }
            }))
            add(AgefansCatalogType("resources", "资源", mutableListOf<AgefansCatalogTypeValue>().apply {
                add(AgefansCatalogTypeValue("全部", "all", true))
                add(AgefansCatalogTypeValue("BDRIP"))
                add(AgefansCatalogTypeValue("AGE-RIP"))
            }))
            add(AgefansCatalogType("order", "排序", agefansCatalogTypeValueOrder()))
        }
    //https://www.agefans.tv/rank?tag=catyear&value=2020&page=2

    @JvmStatic
    fun createRankLink(value: String, page: Int): String {
        val link = "$HOME/rank?tag=catyear&value=${if ("全部" == value) "" else value}&page=${page}"
        Logger.e(link)
        return link
    }

    @JvmStatic
    fun parseRank(html: String, successCallback: (page: AgefansPage<AgefansRank>) -> Unit) {
        kotlin.runCatching {
            val mAgefansPage = AgefansPage<AgefansRank>()
            val agefansItems = mutableListOf<AgefansRank>()
            Jsoup.parse(html).run {
                select(".rank_text").forEach {
                    agefansItems.add(
                        AgefansRank(
                            it.select(".rank_text_idx")?.text()?.toInt() ?: 1,
                            HOME + it.select("a").attr("href"),
                            it.select(".rank_text_name").text(),
                            it.select(".rank_value").text(),
                        )
                    )
                }
                mAgefansPage.data = agefansItems
                handPage(this, mAgefansPage)
                successCallback.invoke(mAgefansPage)
            }
        }.also { Logger.e(it.exceptionOrNull()) }
    }

    fun Element.toAgefansItem() = AgefansItem(
        select(".anime_icon1_name").text(),
        HOME + select("a").attr("href"),
        "${
            select(".anime_icon1_img").let { it.attr("src").ifEmpty { it.attr("data-src") } }.let {
                if (it.startsWith("https") || it.startsWith("http"))
                    it
                else
                    "https:${it}"
            }
        }",
        select(".anime_icon1_img").attr("title")
    )
}